package com.hcloud.system.role.service.impl;

import com.hcloud.common.crud.service.impl.BaseDataServiceImpl;
import com.hcloud.system.api.bean.role.Role;
import com.hcloud.system.authority.entity.AuthorityEntity;
import com.hcloud.system.authority.repository.AuthorityRepository;
import com.hcloud.system.role.entity.RoleAuthEntity;
import com.hcloud.system.role.entity.RoleEntity;
import com.hcloud.system.role.repository.RoleAuthRepository;
import com.hcloud.system.role.repository.RoleRepository;
import com.hcloud.system.role.service.RoleService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

/**
 * @Auther hepangui
 * @Date 2018/11/5
 */
@Service
@AllArgsConstructor
@Transactional(rollbackOn = Exception.class)
public class RoleServiceImpl extends BaseDataServiceImpl<RoleEntity, RoleRepository, Role> implements RoleService {

    private final RoleAuthRepository roleAuthRepository;

    private final AuthorityRepository authorityRepository;

    @Override
    public List<RoleAuthEntity> findRoleAuthEntityByRoleId(String roleId) {
        return roleAuthRepository.findAllByRoleId(roleId);
    }

    @Override

    public void saveAuth(String roleId, String ids) {
        List<RoleAuthEntity> allByRoleId = roleAuthRepository.findAllByRoleId(roleId);
        if (allByRoleId != null && allByRoleId.size() > 0) {
            roleAuthRepository.deleteAll(allByRoleId);
        }
        List<RoleAuthEntity> list = new ArrayList<>();
        Arrays.stream(ids.split(",")).forEach(s -> list.add(RoleAuthEntity.builder().authId(s).roleId(roleId).build()));
        roleAuthRepository.saveAll(list);
    }

    @Override
    public void deleteOne(String id) {
        List<RoleAuthEntity> allByRoleId = roleAuthRepository.findAllByRoleId(id);
        if (allByRoleId != null && allByRoleId.size() > 0) {
            roleAuthRepository.deleteAll(allByRoleId);
        }
        this.deleteById(id);
    }

    @Override
    public List<String> findAuthorityByRoleIds(List<String> roleIds) {
        List<RoleAuthEntity> byRoleIdIn = this.roleAuthRepository.findByRoleIdIn(roleIds);
        List<String> authorityIds = new ArrayList<>();
        List<String> authorities = new ArrayList<>();
//        byRoleIdIn = null;
        if (byRoleIdIn != null && byRoleIdIn.size() > 0) {
            byRoleIdIn.forEach(roleAuthEntitiy ->authorityIds.add(roleAuthEntitiy.getAuthId()));
            List<AuthorityEntity> byIdIn = this.authorityRepository.findByIdIn(authorityIds);
            if (byIdIn != null && byIdIn.size() > 0) {
                byIdIn.forEach(authorityEntity -> authorities.add(authorityEntity.getAuthority()));
            }
        }
        return authorities;
    }
}
